package com.znf4.lucene;

import java.io.IOException;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TrackingIndexWriter;
import org.apache.lucene.search.Query;

public class IndexUtils {  // 索引的帮助类
	
	private  TrackingIndexWriter  trackingIndexWriter ;
	private  static IndexUtils  indexHelp = null ;
	// 初始化参数
	private IndexUtils(){
		IndexManager.getIndexWriter() ;   // 将索引打开
		this.trackingIndexWriter = IndexManager.getTrackingIndexWriter() ;
	}
	
	
	//获取IndexHelp对象；
	static IndexUtils getIndexHelp() {
		if(indexHelp != null){
			return indexHelp;
		}
		indexHelp = new IndexUtils() ;
		return indexHelp ;
	}
	
	
	// 将文本域加入到  索引中 PS : 线程会将其写入到硬盘中
	public boolean addDocument(Document doc){
		try {
			this.trackingIndexWriter.addDocument(doc) ;
			return true ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false ;
	}
	
	
	// 删除 指定查询条件
	public  boolean  deleteDocument(Query query){
		
		try {
			this.trackingIndexWriter.deleteDocuments(query) ;
		    return true ;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false ;
	}

	
	// 删除 指定查询条件
	public  boolean  deleteAll( ){
		try {
			this.trackingIndexWriter.deleteAll() ;
			return true ;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false ;
	}
	
	
	// 修改 文本域
	public boolean updateDocument(Term term, Document doc){
		
		try {
			this.trackingIndexWriter.updateDocument(term, doc) ;
			return true ;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false ;
	}
	
	// 进行 对索引 修改，增加，删除后，写入到硬盘中
	public void commit(){
		try {
			IndexManager.getIndexWriter().commit();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
